<template>
  <view class="pay-container" :data-theme="globPrimary">
    <u-navbar title="订单支付" :custom-back="exit"></u-navbar>
    <view class="pay-wrapper">
      <view class="price">{{ options.payment | formatCurrency }}</view>
      <u-radio-group v-model="paytype" size="40" wrap :active-color="globPrimaryColor">
        <u-radio v-for="(item, index) in payList" :key="index" :name="item">
          <view class="u-flex">
            <u-image width="44rpx" height="44rpx" :src="paywayConfig[item].img"></u-image>
            <view class="text">
              {{ paywayConfig[item].text }}
              <block v-if="item == 'lcnpay'"> ({{ balance | formatCurrency }}) </block>
            </view>
          </view>
        </u-radio>
      </u-radio-group>
    </view>

    <view class="chexk-wrapper">
      <u-checkbox v-model="checked" size="28" label-size="26" :active-color="globPrimaryColor"
        >我已阅读并同意</u-checkbox
      >
      <text
        :style="{ color: globPrimaryColor }"
        @click="
          $u.route('/pages/protocol', {
            key: 'payment',
          })
        "
      >
        《{{ getAgreementTitle('payment') }}》
      </text>
    </view>

    <view class="bottom-placeholder">
      <view class="bottom-navbar">
        <edu-button type="primary" shape="circle" @click="goPay" :disabled="disabled"
          >去支付</edu-button
        >
      </view>
    </view>

    <u-modal
      show-cancel-button
      v-model="showModel"
      :show-title="false"
      cancel-text="放弃"
      confirm-text="继续付款"
      :confirm-color="globPrimaryColor"
      :confirm-style="{ 'border-left': '1px solid #e4e7ed' }"
      @cancel="cancel"
      content="是否放弃本次付款"
    ></u-modal>
    <u-popup
      v-model="showPopup"
      mode="center"
      border-radius="14"
      :safe-area-inset-bottom="true"
      closeable
      :mask="false"
      :mask-close-able="false"
      :z-index="19999"
      :custom-style="{ bottom: keyboardHeight + 'rpx' }"
      :mask-custom-style="{ display: 'none' }"
    >
      <view class="password-wrapper u-border-bottom">
        <view class="title">请输入支付密码</view>
        <u-message-input
          :maxlength="6"
          :dot-fill="true"
          :breathe="false"
          inactiveColor="#303133"
          :value="KeyboardValue"
          disabled-keyboard
        ></u-message-input>
        <view class="btn" v-if="payPwdState == 0" @click="toRoute('/pageUser/setting/editPayPwd')"
          >忘记密码</view
        >
        <view
          class="btn"
          v-else-if="payPwdState == 1"
          @click="toRoute('/pageUser/setting/modifyPayPwd')"
          >忘记密码</view
        >
      </view>
    </u-popup>
    <u-toast ref="uToast" />
    <u-popup v-model="setPwdPopup" mode="center" border-radius="14">
      <view class="setpwd-wrap">
        <view class="text-tips">未设置支付密码</view>
        <view class="goset" @click="toRoute('/pageUser/setting/editPayPwd')">去设置</view>
      </view>
    </u-popup>
    <!-- 键盘 -->
    <u-keyboard
      mode="number"
      v-model="showPopup"
      :dot-enabled="false"
      :tooltip="false"
      :cancel-btn="false"
      :confirm-btn="false"
      :mask-close-able="false"
      @change="onKeyboardChange"
      @backspace="onKeyboardBackspace"
    ></u-keyboard>
  </view>
</template>

<script>
import md5Libs from '@/uview-ui/libs/function/md5'
import setting from '@/settings/projectSetting.js'
import { pay, isWechat } from '@/utils/pay.js'
import { mapGetters, mapState } from 'vuex'
export default {
  data() {
    return {
      setting,
      paytype: '',
      balance: 0,
      payList: [],
      checked: false,
      showModel: false,
      showPopup: false,
      payPwdState: 0,
      options: {},
      setPwdPopup: false,
      balpwd_setus: '',
      keyboardHeight: 440, // 键盘弹出的高度
      KeyboardValue: '',
      paywayConfig: {
        wxpay: {
          text: '微信',
          img: require('@/static/images/order_wechat_icon.png'),
        },
        alipay: {
          text: '支付宝',
          img: require('@/static/images/order_zhifubao_icon.png'),
        },
        lcnpay: {
          text: '余额',
          img: require('@/static/images/order_yue_icon.png'),
        },
      },
      disabled: false,
    }
  },
  computed: {
    ...mapState({
      getGlobOpenid: (state) => state.projectSetting.globOpenid,
    }),
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      getAgreementTitle: 'projectSetting/getAgreementTitle',
    }),
  },
  onLoad(option) {
    this.options = option
  },
  onShow() {
    if (this.setPwdPopup == true) this.setPwdPopup = false
    this.getOrderPay()
  },
  options: { styleIsolation: 'shared' },
  methods: {
    // 支付基础信息
    getOrderPay() {
      this.$edu.api.getOrderPay().then((res) => {
        const { data } = res
        this.balance = data.balance
        this.balpwd_setus = data.balpwd_setus
        if (!this.$u.test.empty(data.payway)) {
          const list = ['wxpay', 'alipay', 'lcnpay']
          const set1 = new Set(data.payway)
          const set2 = new Set(list)
          let str = [...set1].filter((x) => set2.has(x))
          str.sort((prev, next) => {
            return list.indexOf(prev) - list.indexOf(next)
          })
          // #ifdef MP-WEIXIN
          // 小程序隐藏支付宝
          str.splice(
            str.findIndex((item) => item == 'alipay'),
            1
          )
          // #endif
          /* #ifdef H5 */
          // h5 微信内置浏览器隐藏支付宝
          var ua = window.navigator.userAgent.toLowerCase()
          if (ua.match(/micromessenger/i) == 'micromessenger') {
            str.splice(
              str.findIndex((item) => item == 'alipay'),
              1
            )
          }
          /* #endif */
          this.payList = str
          const val = list.find((k) => str.includes(k))
          this.paytype = val
        }
      })
      // 支付密码是否设置-余额支付（忘记密码跳转的地址不同）
      this.$edu.api.getUserBalancePwd().then((res) => {
        this.payPwdState = res.data.exist
      })
    },
    // 支付按钮
    goPay() {
      if (!this.checked) {
        this.$u.toast('阅读并同意' + this.getAgreementTitle('payment'))
        return
      }
      if (this.paytype === '') return
      if (this.paytype == 'lcnpay') {
        if (this.balpwd_setus == 0) {
          this.setPwdPopup = true
        } else {
          var nowprice = parseFloat(this.options.payment)
          if (this.balance - this.options.payment < 0) {
            this.$u.toast('余额不足,请先充值')
          } else {
            this.showPopup = true
          }
        }
      } else {
        this.handlePay()
      }
    },
    // 支付成功跳转页面
    handleReturnUrl(key) {
      switch (key) {
        case 'course':
          this.$u.route({
            type: 'redirectTo',
            url: '/pageCourse/course/details',
            params: {
              id: this.options.id,
            },
          })
          break
        case 'special':
          this.$u.route({
            type: 'redirectTo',
            url: '/pageFound/exam/special/index',
            params: {
              id: this.options.id,
            },
          })
          break
        case 'rollup':
          this.$u.route({
            type: 'redirectTo',
            url: '/pageFound/exam/rollup/index',
            params: {
              id: this.options.id,
              title: this.options.title,
            },
          })
          break
        case 'paper':
          this.$u.route({
            type: 'redirectTo',
            url: '/pageFound/exam/paper/index',
            params: {
              id: this.options.id,
            },
          })
          break
        case 'order':
          this.$u.route({
            type: 'redirectTo',
            url: '/pageUser/order/index',
          })
          break
        case 'vip':
          this.$u.route({
            type: 'redirectTo',
            url: '/pageUser/user/vip',
          })
          break
        case 'mall':
          this.$u.route({
            type: 'redirectTo',
            url: '/pageFound/mall/details',
            params: {
              id: this.options.id,
            },
          })
          break
        default:
          this.$u.route({
            type: 'back',
          })
      }
    },
    // 支付
    handlePay() {
      this.disabled = true
      let params = {
        order_no: this.options.no,
        pay_type: this.paytype,
      }
      /* #ifdef H5 */
      let redirectObj = {
        course: '/pageCourse/course/details',
        order: '/pageUser/order/index',
        vip: '/pageUser/user/vip',
        special: '/pageFound/exam/special/index',
        rollup: '/pageFound/exam/rollup/index',
        paper: '/pageFound/exam/paper/index',
        mall: '/pageFound/mall/details',
      }
      let return_url = ''
      let type = this.options.redirect_type
      if (this.$u.test.empty(redirectObj[type])) {
        params = {
          ...params,
          return_url: '/pageUser/order/index',
        }
      } else {
        let query = {}
        if (this.options.id) {
          query = {
            ...query,
            id: this.options.id,
          }
        }
        if (this.options.title) {
          let query = {
            ...query,
            title: this.options.title,
          }
        }
        if (uni.$u.queryParams(query)) {
          return_url = this.setting.appBaseUrl + redirectObj[type] + uni.$u.queryParams(query)
          params = {
            ...params,
            return_url: return_url,
          }
        } else {
          return_url = this.setting.appBaseUrl + redirectObj[type]
          params = {
            ...params,
            return_url: return_url,
          }
        }
      }
      // 微信公众号支付
      if (isWechat()) {
        if (this.getGlobOpenid) {
          params = {
            ...params,
            openid: this.getGlobOpenid,
          }
          this.$edu.api.postOrderPay(params).then((result) => {
            pay(
              result,
              this.paytype,
              () => {
                let type = this.options.redirect_type
                this.handleReturnUrl(type)
              },
              () => {
                this.$u.route({
                  type: 'redirectTo',
                  url: '/pageUser/order/index',
                  params: {
                    type: 2,
                  },
                })
              }
            )
          })
        } else {
          this.$store.dispatch('projectSetting/setGlobWeixinAppid')
        }
      } else {
        this.$edu.api.postOrderPay(params).then((res) => {
          pay(res, this.paytype, (res) => {
            let encode = encodeURIComponent(params.return_url)
            let paybody = res.data.paybody + '&redirect_url=' + encode
            window.location.href = paybody
          })
        })
      }
      /* #endif */

      // #ifdef MP-WEIXIN
      if (this.getGlobOpenid) {
        params = {
          ...params,
          openid: this.getGlobOpenid,
        }
        this.$edu.api.postOrderPay(params).then((res) => {
          pay(
            res,
            this.paytype,
            () => {
              let type = this.options.redirect_type
              this.handleReturnUrl(type)
            },
            () => {
              this.disabled = false
            }
          )
        })
      } else {
        this.$store.dispatch('projectSetting/setGlobWeixinAppid')
      }
      // #endif

      /* #ifdef APP-PLUS */
      this.$edu.api.postOrderPay(params).then((res) => {
        pay(
          res,
          this.paytype,
          () => {
            let type = this.options.redirect_type
            this.handleReturnUrl(type)
          },
          (err) => {
            this.disabled = false
          }
        )
      })
      /* #endif */

      setTimeout(() => {
        this.disabled = true
      }, 2000)
    },
    // 余额支付，提交支付密码
    handleLcnpay(pass) {
      this.$edu.api
        .postOrderPay({
          order_no: this.options.no,
          pay_type: this.paytype,
          password: md5Libs.md5(pass),
        })
        .then((res) => {
          this.$u.toast(res.msg)
          let type = this.options.redirect_type
          this.handleReturnUrl(type)
        })
      this.showPopup = false
      this.KeyboardValue = ''
    },
    // 返回按钮
    exit() {
      this.showModel = true
    },
    // 确认退出支付,返回到订单
    cancel() {
      let pages = getCurrentPages()
      let page = pages[pages.length - 2]
      if (this.$u.test.empty(page)) {
        let type = this.options.redirect_type
        this.handleReturnUrl(type)
      } else {
        this.$u.route({ type: 'back' })
      }
    },
    toRoute(u, params) {
      this.$u.route(u, params)
    },
    // 键盘点击
    onKeyboardChange(val) {
      this.KeyboardValue += val.toString()
      if (this.KeyboardValue.length == 6) {
        this.handleLcnpay(this.KeyboardValue)
      }
    },
    // 退格键被点击
    onKeyboardBackspace() {
      // 删除value的最后一个字符
      if (this.KeyboardValue.length)
        this.KeyboardValue = this.KeyboardValue.substr(0, this.KeyboardValue.length - 1)
    },
  },
}
</script>

<style lang="scss" scoped>
.pay-wrapper {
  background-color: #fff;
  margin-top: 22rpx;
  padding: 30rpx;
  .price {
    font-size: 40rpx;
    text-align: center;
    font-weight: bold;
    color: $edu-price-color;
  }
  ::v-deep .u-radio-group {
    width: 100%;
    .u-radio__label {
      flex: 1;
    }
    .u-radio {
      padding: 30rpx 0;
      display: flex;
      flex-direction: row-reverse;
      justify-content: space-between;
    }
    .text {
      font-size: 30rpx;
      font-weight: 400;
      color: #606266;
      margin-left: 24rpx;
    }
  }
}
.chexk-wrapper {
  background-color: #fff;
  margin-top: 20rpx;
  padding: 40rpx 30rpx;
  display: flex;
  align-items: center;
  line-height: 1;
  ::v-deep .u-checkbox {
    display: flex;
    line-height: 1;
  }
  ::v-deep .u-checkbox__label {
    margin-right: 0;
  }
  text {
    font-size: 26rpx;
    @include text-color();
  }
}
.bottom-placeholder {
  height: 98rpx;
  /* #ifdef APP-PLUS */
  display: flex;
  justify-content: center;
  /* #endif */
}

.bottom-navbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9;
  background: #ffffff;
  padding: 10rpx 30rpx;
  box-shadow: 0px 2rpx 14rpx 0px rgba(0, 0, 0, 0.06);
  .edu-btn {
    flex: 1 1 auto;
  }
}
.password-wrapper {
  padding: 40rpx 30rpx;
  .title {
    margin-bottom: 50rpx;
    font-size: 36rpx;
    font-weight: 400;
    color: $edu-main-color;
    text-align: center;
  }
  .btn {
    margin-top: 50rpx;
    font-size: 32rpx;
    font-weight: 400;
    @include text-color();
    text-align: center;
  }
  /deep/.u-char-flex {
    border-radius: 8rpx;
    border: 1px solid #b7bac1;
    .u-char-item {
      margin: 0;
    }
    .u-box {
      border: 0;
      border-radius: 0;
    }
    view + view {
      .u-box:after {
        content: ' ';
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        border-left: 1px solid #b7bac1;
        z-index: 2;
      }
    }
  }
}

.radio_item {
  height: auto;
  width: 100%;
  overflow: hidden;

  .radio_li {
    margin-top: 60rpx;
    display: flex;
    justify-content: space-between;
    .left_item {
      width: 60%;
      display: flex;
      height: 44rpx;
      .text {
        @include text-color();
        margin-left: 24rpx;
      }
    }
  }
}

.setpwd-wrap {
  height: 270rpx;
  width: 540rpx;
  background-color: #ffffff;
  font-size: 36rpx;
  .text-tips {
    height: 170rpx;
    width: 100%;
    border-bottom: 1px solid #dddddd;
    line-height: 170rpx;
    text-align: center;
    color: #303133;
  }
  .goset {
    height: 99rpx;
    line-height: 99rpx;
    width: 100%;
    text-align: center;
    color: #5191ff;
  }
}
</style>
